﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Spring.Data.NHibernate.Generic;
using NHibernate.Criterion;
using log4net;

namespace FJASPX.Framwork.Query
{
    [Serializable]
    public class CriteriaQueryTemplate
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(CriteriaQueryTemplate));
        private HibernateTemplate ht = new HibernateTemplate();
        public ISessionFactory SessionFactory { get; set; }
        public CriteriaQueryTemplate()
        {
            ht.SessionFactory = SessionFactory;
        }
        public Page PagedQuery(DetachedCriteria detachedCriteria, int startIndex, int pageSize, List<Order> orders)
        {
            Page page = null;
            List<object> list = new List<object>();
            ICriteria query = detachedCriteria.GetExecutableCriteria(ht.SessionFactory.OpenSession());
            ICriteria queryPage = CriteriaTransformer.Clone(query);
            //获取记录总数
            int recordCount = Convert.ToInt32(query.SetProjection(Projections.RowCount()).UniqueResult());

            //设置排序
            if (orders != null)
            {
                foreach (Order o in orders)
                {
                    queryPage.AddOrder(o);
                }
            }
            queryPage.SetFirstResult((startIndex - 1) * pageSize);
            queryPage.SetMaxResults(pageSize);
            list = (List<object>)queryPage.List<object>();
            if (recordCount == 0)
            {
                page = Page.EMPTY_PAGE;
            }
            else
            {
                page = new Page((long)startIndex, (long)recordCount, pageSize, list);
            }
            return page;
        }
        public int RowCountQuery(DetachedCriteria detachedCriteria)
        {
            int recordCount = 0;
            try
            {
                ICriteria criteria = detachedCriteria.GetExecutableCriteria(ht.SessionFactory.OpenSession());
                //获取记录总数
                recordCount = Convert.ToInt32(criteria.SetProjection(Projections.RowCount()).UniqueResult());
                return recordCount;
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            return recordCount;
        }
    }
}
